package com.ghostbusters.fingertrack.control;

import java.util.HashMap;
import java.util.Map;

import com.ghostbusters.fingertrack.calibration.Calibration;
import com.ghostbusters.fingertrack.calibration.Signature;
import com.ghostbusters.fingertrack.calibration.SymbolCalibrater;
import com.ghostbusters.fingertrack.wii.IRPoint;
import com.ghostbusters.fingertrack.wii.WiiMain;

public class CalibrationControl<E> {

	private Map<E, SymbolCalibrater<E>> symbolToSymbolCalibrater = new HashMap<E, SymbolCalibrater<E>>();
	private Calibration<E> calibration;

	/**
	 * This is the entry point for Justin/the GUI! Pass in a symbol, that
	 * contains an object like "a" and it will create a signature and added the
	 * pair to the calibration.
	 * 
	 * @param symbol
	 *            an object, can be a string
	 * @param calibration
	 *            the calibration to be added to, it can be null
	 */

	// for Justin's viewing viewing pleasure of how to use this
	public static void main(String[] args) throws Exception {

		// can be a string, or object or anything
		Character symbol = 'a';

		// KEEP THIS CALIBRATION, this is how the symbol signature will be
		// passed back.
		Calibration<Character> calibration = new Calibration<Character>();
		System.out.println("Start calibration: " + calibration);

		// pass in your calibration!
		CalibrationControl<Character> controller = new CalibrationControl<Character>(
				calibration);

		// actionPerformed - onStartCalibratingButton
		controller.startCalibratingSymbol(symbol);

		// actionPerformed - onEndCalibratingButton
		controller.endCalibratingSymbol(symbol);
		
		System.out.println("Ending calibration: " + calibration);
	}

	public CalibrationControl(Calibration<E> calibration) {
		this.calibration = calibration;
	}

	public void startCalibratingSymbol(E object) {
		calibration.add(object, new Signature());
		SymbolCalibrater<E> symbolCalibrater = new SymbolCalibrater<E>(object);

		symbolToSymbolCalibrater.put(object, symbolCalibrater);

	}

	/**
	 * Ends the calibration of a symbol
	 * 
	 * @param object
	 * @throws Exception
	 *             Throws when the symbolCalibrator does not exist or when the
	 *             Symbol you passed in does not exist
	 */
	public void endCalibratingSymbol(E object) {
		if (!symbolToSymbolCalibrater.keySet().contains(object)) {
			// throw new Exception("Symbol " + object+
			// " did not have a startCalibratingSymbol call");
		}
		SymbolCalibrater<E> symbolCalibrator = symbolToSymbolCalibrater
				.get(object);

		try {
			WiiMain.unsubscribe(symbolCalibrator);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		calibration.add(object, symbolCalibrator.getSignature());

	}

}
